package com.hgvip.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by arnold.zhu on 2017/7/27.
 *
 * <p>测试用Controller，不用看</p>
 */
@RestController
@RequestMapping("/test")
public class TestController {

    @RequestMapping(value = "/testCookie")
    public Object testCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        String userName = getCookie(cookies, "userName");
        String userAge = getCookie(cookies, "userAge");
        if (userName == null) {
            response.addCookie(new Cookie("userName", "zhangsan"));
        }
        if (userAge == null) {
            response.addCookie(new Cookie("userAge", "18"));
        }
        return response.getHeaders("Set-Cookie");
    }

    private String getCookie(Cookie[] cookies, String key) {
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (key.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

}
